package com.herui.iot.app;

import android.content.Context;
import android.text.TextUtils;

import com.herui.device_lib.DeviceLibApp;
import com.herui.sdyu_lib.aliyun.oss.AliOssApp;
import com.herui.sdyu_lib.base.BaseAppcation;
import com.herui.sport_care.config.AppConfig;
import com.herui.sport_care.ui.view.ecg.bean.EcgStyle;
import com.herui.sport_care.utils.StorageUtils;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


/**
 * Created by amanda.shan on 2022/10/18.
 */
public class SportCareApp extends BaseAppcation {

    private final static String TAG = SportCareApp.class.getSimpleName();

    private DeviceLibApp deviceLibApp;

    private boolean enterMain;

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.t(TAG).i("SmartWatchApp onCreate");

        EcgStyle.init(this);
        try {
            StorageUtils.init();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (!AppConfig.DEBUG) {
            initbugly();
        }

        deviceLibApp = new DeviceLibApp();
        deviceLibApp.init(this);
        AliOssApp.getInstance().init(this);

    }

    public boolean isEnterMain() {
        return enterMain;
    }

    public void setEnterMain(boolean enterMain) {
        this.enterMain = enterMain;
    }

    public DeviceLibApp getDeviceLibApp() {
        return deviceLibApp;
    }

    private void initbugly() {
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));

        // true 代表debug 模式
        CrashReport.initCrashReport(context, "c91469a055", true, strategy);
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}
